package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService{


    // 微信服务器openid调用获取地址
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录C端 实现
     * @param userLoginDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User login(UserLoginDTO userLoginDTO) {

        // 包装请求参数
        HashMap<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",userLoginDTO.getCode());
        param.put("grant_type","authorization_code");

        // 获取openid;
        String response = HttpClientUtil.doGet(WX_LOGIN_URL, param);
        JSONObject jsonObject = JSON.parseObject(response);
        String openid = jsonObject.getString("openid");
        if(openid == null || openid.equals("")){
            throw new BaseException(MessageConstant.LOGIN_FAILED);
        }

        // 通过openid判断用户是否存在
        User user = userMapper.getByOpenid(openid);

        // 用户不存在自动注册账户
        if (user == null){
            // 注册
            User registerUser = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(registerUser);
            log.info("客户端用户注册成功:{}",registerUser);
            return registerUser;
        }


        return user;
    }



}
